/**
 * @Author: lusx
 * @Date:   07-03-2019 10:26:52
 * @Project: Govern督办
 * @Last modified by:   lusx
 * @Last modified time: 29-04-2019 01:51:30
 */
import React from "react";
import { observable, action } from "mobx";
import { ShareAuth, ListViewPage } from "weaver-mobile-page";
import { Toast, Tools, ActionSheet,Bubble } from "weaver-mobile";
import Validator from 'validatorjs/dist/validator.min.js';
import * as Apis from "../../apis/govern";
import agent from "./agent.js";
import btnStore from "./btnStore.js";
import btnTypeStore from "./btnTypeStore.js";
import shareStore from "./shareStore.js";
import cbData from "../data/cbStore.js";
import fkData from "../data/fkStore.js";
import { SupStore } from "../supStore.js";
import { MainStore } from "../main/mainStore.js";
import {forwardViewForm} from '../../../../mobile4mobx/workflowForm/util/forwardPage';
import GovernConstant from '../../util/index';
import {validatorRegister} from '../../util/tools';
const getLabel = Tools.getLabel;
//动作面板
export default class ActionSheetStore extends SupStore {
  btnType = "";
  isRight = false;
  id = "";
  //@observable decomposeTaskLayoutData = [];
  @observable mainStore={};
  path = '';
  constructor(store) {
    super();
    this.mainStore = store;
    this.handleSubmit = this.handleSubmit.bind(this);
    //this.getDecomposeTaskLayout = this.getDecomposeTaskLayout.bind(this);
    this.goOn = this.goOn.bind(this);
    this.updateListViewStore = this.updateListViewStore.bind(this);
    this.clearData = this.clearData.bind(this);
  }
  /**
   *
   * @param {参数类型} {"message":"","id":String} 参数说明  列表每行id;
   * @return {返回值类型}
   */
  @action
  getActionBtn = params => {
    const { message, historyPush, path, ...id } = params;
    this.path = path;
    this.id = params.id;
    agent.Btn.root(id)
      .then(({ status, quickBtn }) => {
        if (status === '1') {
          this.isRight = true;
          let btnEle = btnStore.GetBtnEle(quickBtn, "0");
          return btnEle;
        } else {
          this.isRight = false;
        }
      })
      .then(btnEle => {
        if(btnEle.length === 0){
          Bubble.warning('您没有操作权限', 2, {}, 1);
          return false;
        }else{
          this.showShareActionSheetMulpitleLine({
            sheetBtns: btnEle,
            message: message,
            isRight: this.isRight,
            historyPush: historyPush,
            path: path,
            ...id
          });
        }
      })
      .catch(error => {
        Toast.fail(error);
      })
      .finally(() => {
        this.isRight = false;
      });
  };
  /**
   * ActionSheet 动作面板
   * @param {参数类型} {"sheetBtns":[{"icon":<></>,"title":""}],"message":"",id:""} 参数说明  按钮数据源;动作面板的title;点击行信息的o;
   * @return {返回值类型}
   */
  @action
  showShareActionSheetMulpitleLine = params => {
    const data = btnStore.SetRowBtnNum(params);
    const { historyPush, path } = params;
    ActionSheet.showShareActionSheetWithOptions(
      {
        options: data,
        message: (
          <div>
            <div>{params.message}</div>
            {this.isRight === false && (
              <div>{getLabel("555", "您没有权限")}</div>
            )}
          </div>
        ),
        maskClosable: true,
        className : 'myclassName',
      },
      (buttonIndex, rowIndex) => {
        this.btnType =
          buttonIndex > -1 ? data[rowIndex][buttonIndex].key : "cancel";
        if (this.btnType !== "cancel") {
          const _this = this;
          Apis.getActionSetting({ taskid: params.id, actiontype: this.btnType }).then((data) => {
            if (data.status === "1") {
              if (data.isShowModel === false) {
                forwardViewForm({requestid:data.newrequestid, workflowid: data.flowid,taskid: params.id,actiontype: this.btnType});
              } else {
                this.list.clearData();
                btnTypeStore.BtnTypes[this.btnType]({
                  btnType: this.btnType,
                  id: params.id,
                  handle: this.updateListViewStore
                })
                  .then(data => {
                    if (data) {
                      _this.newGform();
                      _this.actions[this.btnType]({ 'data': data, 'path': path, 'historyPush': historyPush, 'id': params.id });
                      return Promise.resolve();
                    }
                  })
                  .catch(error => {
                    Toast.fail(error);
                  });
              }
            }
          })

        }
      }
    );
  };
  actions = {
    "3": ({ data, path, historyPush }) => {
      if(Array.isArray(data.condition1)){
        data.condition1[0].items = GovernConstant.setUploadfileid(data.condition1[0].items);
      }
      this._setRichEValue(data.condition1);
      this.initGForm(data.condition1, `${path}/govern`);
      historyPush(`${path}/govern`);
    }, //变更
    "4": action(({ data, path, historyPush, id }) => {
      // historyPush(`${path}/govern?id=${id}`);
      historyPush(`${path}/govern`);
      this.decomposeTaskLayoutData = data.condition2;
      if(Array.isArray(data.condition2)){
        data.condition2[0].items = GovernConstant.setUploadfileid(data.condition2[0].items);
      }
      this._setRichEValue(data.condition2);
      this.initGForm(data.condition2, `${path}/govern`);
      // historyPush(`${path}/govern?id=${id}`);
      historyPush(`${path}/govern`);
    }), //分解
    "5": ({ data, path, historyPush }) => {
      this.setSliderValue(data.progress);
      this._setRichEValue(fkData.Data.condition1);
      this.initGForm(fkData.Data.condition1, `${path}/govern`);
      const obj = {
        topic: {
          value: data.title,
          id: "topic"
        }
      };
      this.gform.updateFields(obj);
      historyPush(`${path}/govern`);
    }, //反馈
    "8": ({ data, path, historyPush }) => {
      this._setRichEValue(cbData.Data.condition1);
      this.initGForm(cbData.Data.condition1, `${path}/govern`);
      const obj = {
        topic: {
          value: data.title,
          id: "topic"
        }
      };
      this.gform.updateFields(obj);
      historyPush(`${path}/govern`);
    }, //催办
    "11": ({data, path, historyPush }) => {
      this.listGetDate(data.sessionkey);
      this.shareCondition = shareStore.Data.shareCondition;
      if(data.appDetachDisableAll){
        this.shareCondition[0].options.splice(4,1);//去除所有人
      }
      // this.shareAuthRoute = new ShareAuth.Store({
      //   route: `${path}/share`,
      //   id: "list"
      // });
      this.setshareAuthRoute(path);
      historyPush(`${path}/share`);
    }, //共享
  };
  @action
  setshareAuthRoute = (path)=>{
    this.shareAuthRoute = new ShareAuth.Store({
      route: `${path}/share`,
      id: "list"
    });
  }
  @action
  listGetDate=(sessionkey)=>{
    this.list.clearData();
    // this.list = new ListViewPage.Store({ route: '/governList' ,id:'sharelist'});
    // console.log(123)
    let dataKey = {
      'dataKey': sessionkey
    }
    this.list.getData(dataKey);
  }
  //更新列表
  @action
  updateListViewStore() {
    switch (this.btnType) {
      case "1003"://删除后更新列表
        this.mainStore.listViewStore = new ListViewPage.Store({ route: this.path });
        this.mainStore.listViewStore.getData(this.mainStore.dataKey);
        break;
      default:
        null;
    }

  }
  //获取分解任务的form布局
  // @action
  // getDecomposeTaskLayout(historyPush, path) {
  //   this.initGForm(this.decomposeTaskLayoutData, `${path}/govern`);
  //   historyPush(`${path}/govern`);
  // }
  //是否继续执行
  validatorRegister = () => {
    // let {startdate='',starttime='',endtime='',astartdate='',aenddate='',astarttime='',aendtime=''} = this.gform.formParams;
    // startdate = startdate.padStart(10, '1000-01-01');
    // astartdate = astartdate.padStart(10, '1000-01-01');
    // starttime = starttime.padStart(4, '00:00');
    // astarttime = astarttime.padStart(4, '00:00');
    // endtime = endtime.padStart(4, '00:00');
    // aendtime = aendtime.padStart(4, '00:00');
    // const start = startdate.split(" ")[0].concat(" ",starttime);
    // const astart = astartdate.split(" ")[0].concat(" ",astarttime);
    // Validator.register('endafterdate', function(value) {
    //   value = value.split(" ")[0].concat(" ",endtime);
    //   return new Date(start.replace(/-/g, "/")) <= new Date(value.replace(/-/g, "/"));
    // }, 'The :Start date time cannot be greater than attribute time');
    // Validator.register('aendafterdate', function(value) { 
    //   value = value.split(" ")[0].concat(" ",aendtime);
    //   return new Date(astart.replace(/-/g, "/")) <= new Date(value.replace(/-/g, "/"));
    // }, 'The :aStart date time cannot be greater than attribute time');
    validatorRegister(this.gform);
  }
  @action
  goOn(btnType) {
    //return Promise.resolve(this.doValidate());
    if(btnType !== "11"){
      this.validatorRegister();
      let data = this.gform.formParams;
      let rules = {
        enddate: 'endafterdate',
        aenddate: 'aendafterdate',
      };
      let validation = new Validator(data, rules);
      if(validation.passes()){
        return Promise.resolve(this.doValidate());
      }else if(validation.fails()){
        //console.log("validation.errors",validation.errors.all()) ;
        Bubble.warning(getLabel("511480", "开始日期时间不能大于结束日期时间"), 2, {}, 1);
        return Promise.resolve(false);
      }
    }else{
      return Promise.resolve(true);
    }
  }
  //提交方法
  handleSubmit() {
    this.inProgress = true;
    this.gform.updateFields(this.getFormData());
    const value = {
      "3": { ...this.gform.formParams },
      "11": this.shareSubData,
      "8": { ...this.gform.formParams, ...{ content: this.richEValue.remark } },
      "5": {
        ...this.gform.formParams,
        ...{ content: this.richEValue.remark },
        ...{ progress: this.sliderValue }
      },
      "4": { ...this.gform.formParams }
    };
    const v = value[this.btnType];
    return this.goOn(this.btnType)
      .then(data => {
        if (data === true) {
          //this.list.clearData(); 19.10.29 lusx 会导致共享完返回的共享页面空白
          return btnTypeStore.SubTypes[this.btnType]({
            id: this.id,
            btnType: this.btnType,
            v: v
          });
        } else {
          return false;
        }
      })
      .catch(error => {
        Toast.fail(error);
      })
      .finally(
        action(() => {
          this.inProgress = false;
        })
      );
  }
  clearData() {
    //this.decomposeTaskLayoutData = [];
    this.resetFields();
    this.richEValue = {};
  }
}
